<template>
  <a-spin :spinning="spinning" tip="加载中...">
    <a-icon slot="indicator" type="loading" style="font-size: 24px" spin />
    <div class="analysis">
      <div class="table mt20">
        <div class="top-filter flex-between mb10">
          <div
            class="strong fs16 mrSemiBold flex-center"
            style="color: #110000"
          >
            <div class="outer">
              <div class="inner"></div>
            </div>
            用户管理
          </div>
        </div>

        <div class="consultation-block">
      <div class="table" v-loading="tableLoading">
        <el-table size="mini" :data="tableData" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="username" label="用户名"> </el-table-column>
          <el-table-column prop="password" label="密码"> </el-table-column>
          <el-table-column prop="score" label="积分"> </el-table-column>
          <el-table-column prop="type" label="角色" :formatter="formatRole"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                type="warning"
                size="mini"
                v-if="scope.row.username !== 'admin'"
                @click="updateData(scope.row)"
                >修改</el-button
              >
              <el-button
                type="danger"
                size="mini"
                v-if="scope.row.username !== 'admin'"
                @click="deleteData(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="isVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input disabled type="text" v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            :disabled="currentRow.username === 'admin'"
            type="text"
            v-model="ruleForm.password"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
      </div>
    </div>
  </a-spin>
</template>

<script>
import {
  getUser,
  deleteUser,
  updateUser,
} from "../../../service";
import moment from "moment";
export default {
  name: "Price",
  watch: {
    $route(to) {
      if (to.path === "/page/process") {
        this.refreshTable();
        this.userInfo = JSON.parse(localStorage.getItem('articleWebInfo'))
      }
    },
  },
  mounted() {
    if (!localStorage.getItem("articleWebInfo")) {
      this.$message.error('请先登录')
      this.$router.push('/login')
      return
    }
    this.userInfo = JSON.parse(localStorage.getItem('articleWebInfo'))
    this.refreshTable();
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableLoading: false,
      isVisible: false,
      dialogTitle: "",
      ruleForm: {
        username: "",
        password: "",
        likes: []
      },
      userInfo: {},
      rules: {
        password: [{ validator: validatePass, trigger: "blur" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
      },
      json_fields: {},
      columns: [],
      inputValue: "",
      inputVisible: false,
      isVisible2: false,
      tableDataModal: [],
      columnModel: [],
      title: "",
      currentRow: {},
      spinning: false
    };
  },
  methods: {
    handleClose() {
      this.isVisible = false;
    },
    handleCurrentChange() {},
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateUser(this.ruleForm.id, {
            password: this.ruleForm.password,
          }).then((res) => {
            if (res.code === 200) {
              this.$message.success("编辑成功");
              this.refreshTable();
              this.isVisible = false;
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    refreshTable() {
      console.log({
        page: this.currentPage,
        pageSize: this.pageSize,
        id: this.userInfo.admin ? '' : this.userInfo.id
      })
      getUser({
        page: this.currentPage,
        pageSize: this.pageSize,
        id: this.userInfo.admin ? '' : this.userInfo.id
      }).then((res) => {
        this.tableData = res.code === 200 ? res.data.data : [];
      });
    },
    updateData(row) {
      console.log(row);
      this.currentRow = row;
      this.dialogTitle = "修改";
      this.ruleForm = {
        ...row,
      };
      this.isVisible = true;
    },
    deleteData(row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteUser(row.id).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.refreshTable();
            }
          });
        })
        .catch(() => {});
    },
    formatRole(row) {
      if (row.admin) {
        return '管理员'
      } else {
        return '普通用户'
      }
    }
  },
};
</script>

<style lang="less" scoped>
  .consultation {
    padding: 20px;
  }
.table {
  background: #fff;
  padding: 20px;
}
</style>
